﻿Imports System.Text

''' <summary>
''' ルートテーブルマッピング
''' </summary>
''' <remarks></remarks>
Public Class RootTableMap
    Inherits TableMap

    ''' <summary>
    ''' ルートテーブルマップかどうかを示します
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Overrides ReadOnly Property IsRoot As Boolean
        Get
            Return True
        End Get
    End Property

    ''' <summary>
    ''' クエリ
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Query As IQuery

    ''' <summary>
    ''' SELECTクエリテキストに変換します
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ToSelectQuery() As String
        Dim s As New StringBuilder
        s.Append(Me.ToSelectString)
        s.AppendLine()
        s.Append(Me.ToFromString)
        Return s.ToString
    End Function

    ''' <summary>
    ''' SELECTテキストに変換します
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ToSelectString() As String
        Return "SELECT " & Me.ToColumnString
    End Function

    ''' <summary>
    ''' FROMテキストに変換します
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ToFromString() As String
        Dim jsql = Me.ToJoinString

        Dim fsql As New StringBuilder
        fsql.AppendFormat("FROM {0} T0", Me.Definition.EntityName)
        If String.IsNullOrEmpty(jsql) = False Then
            fsql.AppendLine()
            fsql.Append(jsql)
        End If

        Return fsql.ToString
    End Function

    ''' <summary>
    ''' エンティティに変換します
    ''' </summary>
    ''' <param name="reader"></param>
    ''' <returns></returns>
    ''' <remarks>マッピング処理</remarks>
    Public Function ToEntity(reader As IDataRecord) As Object
        If reader Is Nothing Then Throw New ArgumentNullException("reader")

        Dim row As New Dictionary(Of String, Object)
        For i As Integer = 0 To reader.FieldCount - 1
            row.Add(reader.GetName(i), reader.GetValue(i))
        Next

        Dim instance = Me.ToEntity(row)
        Return instance
    End Function

    ''' <summary>
    ''' エンティティに変換します
    ''' </summary>
    ''' <param name="row"></param>
    ''' <returns></returns>
    ''' <remarks>マッピング処理</remarks>
    Private Function ToEntity(row As Dictionary(Of String, Object)) As Object
        'インスタンス作成
        Dim rt = Me.Definition.EntityType
        Dim instance = Activator.CreateInstance(rt)

        Me.ExecuteMapping(instance, row)

        Return instance
    End Function
End Class
